Popular Searches
Popular Course Categories
Popular Courses

Accessing Location and GPS Services

Accessing Location and GPS Services

Device Features and Native Capabilities

Accessing Location and GPS Services in React Native – Detailed Notes

Course: React Native Training

Topic: Accessing Location and GPS Services in React Native

Course Link: React Native Training – JustAcademy

Demo Registration Link: Register for a Course Demo

Academy Website: JustAcademy Official Website


1. Introduction to Location and GPS Services

Location services allow mobile applications to determine the approximate or precise geographical position of a device. React Native developers can use location APIs and compatible libraries to access location information from Android and iOS devices.

GPS stands for Global Positioning System. It is a satellite-based navigation system that helps devices estimate their position. However, mobile location services do not rely exclusively on GPS. Depending on the device and operating system, location estimates may also use Wi-Fi networks, cellular networks, Bluetooth signals, and other available information.

React Native applications can use location information to display maps, find nearby places, calculate routes, support delivery tracking, and provide location-aware experiences.

1.1 What Is Location Tracking?

Location tracking is the process of obtaining one or more location measurements over time. An application might retrieve the current position once or subscribe to updates while a user is moving.

For example, a food delivery application may retrieve the customer's location to identify nearby restaurants. A navigation application may continue receiving location updates to show movement along a route.

1.2 Importance of Location Services

  • Enable location-aware mobile applications.
  • Support navigation and route planning.
  • Help users discover nearby shops, restaurants, hospitals, and other services.
  • Support delivery, transport, and logistics workflows.
  • Provide location-based reminders and alerts.
  • Help fitness applications record routes and outdoor activities.
  • Improve contextual recommendations when users explicitly allow location access.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Understand GPS and mobile location services.
  • Explain latitude, longitude, altitude, accuracy, and heading.
  • Install and configure a location library in React Native.
  • Request foreground location permissions.
  • Retrieve the current and last-known device location.
  • Subscribe to location updates and clean up subscriptions.
  • Understand geocoding and reverse geocoding.
  • Distinguish foreground and background location access.
  • Handle disabled GPS, denied permissions, and location errors.
  • Apply privacy, battery-efficiency, and testing best practices.

3. Understanding GPS and Mobile Location Technology

3.1 What Is GPS?

GPS is a satellite-based positioning system that enables a compatible receiver to estimate its position using signals from satellites. A phone may use GPS and other available location sources to produce a location estimate.

3.2 GPS vs. General Location Services

Feature GPS General Location Services
Meaning A satellite-based positioning system. Operating-system functionality that provides location estimates.
Data sources GPS satellite signals. May combine satellite, Wi-Fi, cellular, and other supported sources.
Indoor performance Can be limited when satellite signals are weak. May provide an estimate using other available sources.
Battery use Depends on receiver activity and device implementation. Depends on requested accuracy, update frequency, and available providers.
Application use Satellite-based positioning. Maps, nearby search, navigation, and other location-aware features.

3.3 Factors That Affect Location Accuracy

  • Availability and strength of satellite signals.
  • Indoor environments and tall buildings.
  • Weather and surrounding physical obstructions.
  • Device hardware and operating-system behavior.
  • Permission level and accuracy settings.
  • Wi-Fi and cellular network availability.
  • Movement, signal interference, and time required to obtain a location fix.

A location result is an estimate, not a guarantee of a person's exact physical position. Applications should consider the reported accuracy before using coordinates for important decisions.

4. Understanding Location Coordinates

Location APIs commonly return a collection of geographical and measurement values.

Property Meaning Example Use
Latitude Angular position north or south of the equator. Identifying a point on Earth.
Longitude Angular position east or west of the prime meridian. Identifying a point on Earth.
Altitude Estimated height above a reference level, where available. Outdoor activity measurements.
Accuracy Estimated uncertainty of the horizontal location, usually expressed in metres. Determining whether a result is sufficiently accurate.
Heading Direction of movement or device orientation, depending on the API. Navigation interfaces.
Speed Estimated speed, usually expressed in metres per second where provided. Movement tracking.
Timestamp Time associated with a location measurement. Identifying the age of a location result.

4.1 Example of a Location Object

{
  "coords": {
    "latitude": 19.0760,
    "longitude": 72.8777,
    "altitude": null,
    "accuracy": 20,
    "heading": null,
    "speed": null
  },
  "timestamp": 1790000000000
}

This is an illustrative example of a location-object structure, not a live device reading. Actual values can differ, and some properties may be null or unavailable.

5. Setting Up Location Services in React Native

For Expo-based React Native applications, the expo-location package provides APIs for requesting permissions, retrieving coordinates, watching location updates, and performing geocoding operations.

5.1 Install Expo Location

npx expo install expo-location

Using the Expo installation command helps select a version compatible with the project's Expo SDK.

5.2 Import the Location Module

import * as Location from 'expo-location';

The imported module exposes functions for checking permissions, requesting location access, obtaining coordinates, and subscribing to updates.

5.3 Configure Native Permissions

Location permission configuration depends on the project and the type of access required. Expo config plugins can configure native settings, while bare React Native projects may require direct Android and iOS configuration.

For iOS, the application needs an appropriate location usage description. Android applications generally require the relevant approximate or precise location permission. Background access requires additional configuration and authorization.

For official configuration details, see the Expo Permissions Guide and Expo Location Documentation.

6. Understanding Location Permissions

Location data is sensitive. The operating system allows users to control whether applications can access approximate or precise location information.

6.1 Foreground Location Permission

Foreground permission allows an application to access location while it is being used, according to the platform's rules. It is usually the correct starting point for features such as showing the user's current position on a map.

6.2 Background Location Permission

Background permission allows supported location operations to continue when the application is not actively visible. It may be needed for a clearly disclosed route-tracking or geofencing feature.

Background access is subject to stricter operating-system rules, native configuration, battery restrictions, and app-store policies. Request it only when the feature genuinely requires it.

6.3 Approximate and Precise Location

  • Approximate location: Provides a general area and may be sufficient for finding nearby services.
  • Precise location: Provides a more accurate position when the operating system and user permit it.

Do not request precise location if approximate location is sufficient for the application feature.

6.4 Permission-Handling Best Practices

  • Explain why the application needs location access.
  • Request permission when the user starts a location-related feature.
  • Check the permission result before requesting coordinates.
  • Handle denied and restricted access gracefully.
  • Provide a manual location-entry alternative when possible.
  • Direct users to system settings when appropriate and permitted.
  • Never assume that a previously granted permission remains granted forever.

7. Getting the Current Location

The current-location API requests a new location measurement. The operation can take several seconds, depending on signal availability, requested accuracy, and the environment.

7.1 Example: Get the Current Location

import React, { useState } from 'react';
import { Button, Text, View } from 'react-native';
import * as Location from 'expo-location';

export default function CurrentLocationScreen() {
  const [location, setLocation] = useState(null);
  const [message, setMessage] = useState('');

  async function getCurrentLocation() {
    try {
      setMessage('Checking location permission...');

      const permission =
        await Location.requestForegroundPermissionsAsync();

      if (!permission.granted) {
        setMessage('Location permission was denied.');
        return;
      }

      setMessage('Getting current location...');

      const result = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.Balanced
      });

      setLocation(result);
      setMessage('Location retrieved successfully.');
    } catch (error) {
      console.error('Location error:', error);
      setMessage('Unable to retrieve location.');
    }
  }

  return (
    <View>
      <Button
        title="Get Current Location"
        onPress={getCurrentLocation}
      />

      <Text>{message}</Text>

      {location ? (
        <>
          <Text>
            Latitude: {location.coords.latitude}
          </Text>
          <Text>
            Longitude: {location.coords.longitude}
          </Text>
          <Text>
            Accuracy: {location.coords.accuracy ?? 'Unavailable'} metres
          </Text>
        </>
      ) : null}
    </View>
  );
}

7.2 Explanation of the Code

  1. useState stores the returned location and status message.
  2. requestForegroundPermissionsAsync() asks for foreground location authorization.
  3. The application checks whether permission was granted.
  4. getCurrentPositionAsync() requests a location measurement.
  5. The returned coordinates are stored in state.
  6. The interface displays latitude, longitude, and estimated accuracy.
  7. The catch block handles errors without crashing the screen.

7.3 Choosing an Accuracy Level

Accuracy Strategy When to Use It
Lowest or low accuracy When a rough position is sufficient.
Balanced accuracy When a reasonable balance between accuracy and resource use is needed.
High accuracy When the feature needs a more precise estimate and the device can provide it.
Best navigation accuracy When the library supports it and the use case genuinely requires the highest available accuracy.

Accuracy constants and supported options depend on the installed library version. Higher accuracy does not guarantee a perfect result and may increase battery consumption or acquisition time.

8. Getting the Last-Known Location

The last-known location is a previously recorded location available from the operating system. It may return faster than requesting a new measurement, but it can be stale or unavailable.

8.1 Example: Retrieve the Last-Known Position

import * as Location from 'expo-location';

async function getLastKnownLocation() {
  try {
    const permission =
      await Location.requestForegroundPermissionsAsync();

    if (!permission.granted) {
      return null;
    }

    const location =
      await Location.getLastKnownPositionAsync({
        maxAge: 60000,
        requiredAccuracy: 100
      });

    if (!location) {
      console.log('No suitable last-known location available.');
      return null;
    }

    console.log('Latitude:', location.coords.latitude);
    console.log('Longitude:', location.coords.longitude);

    return location;
  } catch (error) {
    console.error('Unable to get last-known location:', error);
    return null;
  }
}

8.2 When to Use It

  • When the interface needs to show a recent approximate position quickly.
  • When an immediate fresh GPS fix is not essential.
  • When an application wants to display cached location while requesting an updated position.

Always consider the timestamp and accuracy of a last-known location. Do not use a stale location as if it were guaranteed to represent the device's current position.

9. Watching Continuous Location Updates

Some applications need to receive location updates while a feature is active. Examples include navigation, an outdoor exercise tracker, or a delivery workflow where the user has explicitly started tracking.

9.1 Example: Subscribe to Location Changes

import React, { useEffect, useState } from 'react';
import { Text, View } from 'react-native';
import * as Location from 'expo-location';

export default function LocationTrackingScreen() {
  const [location, setLocation] = useState(null);
  const [message, setMessage] = useState('Starting location service...');

  useEffect(() => {
    let subscription;
    let active = true;

    async function startTracking() {
      try {
        const permission =
          await Location.requestForegroundPermissionsAsync();

        if (!permission.granted) {
          if (active) {
            setMessage('Location permission was denied.');
          }
          return;
        }

        subscription = await Location.watchPositionAsync(
          {
            accuracy: Location.Accuracy.Balanced,
            distanceInterval: 10,
            timeInterval: 5000
          },
          (position) => {
            if (active) {
              setLocation(position);
              setMessage('Receiving location updates.');
            }
          }
        );
      } catch (error) {
        if (active) {
          setMessage('Unable to start location tracking.');
        }
        console.error('Tracking error:', error);
      }
    }

    startTracking();

    return () => {
      active = false;
      subscription?.remove();
    };
  }, []);

  return (
    <View>
      <Text>{message}</Text>
      {location ? (
        <>
          <Text>
            Latitude: {location.coords.latitude}
          </Text>
          <Text>
            Longitude: {location.coords.longitude}
          </Text>
        </>
      ) : null}
    </View>
  );
}

This example demonstrates foreground tracking. The distance and time settings are hints or platform-dependent options, not guarantees that updates will arrive at exact intervals. Production applications should also consider whether tracking should start automatically or only after an explicit user action.

9.2 Why Cleanup Is Important

  • Prevents unnecessary location updates.
  • Reduces battery consumption.
  • Helps avoid duplicate subscriptions.
  • Reduces state updates after a component unmounts.
  • Stops location collection when the relevant feature is no longer active.

10. Checking Whether Location Services Are Enabled

Permission and service availability are different. A user may grant location permission while device location services remain disabled.

10.1 Example: Check Location Services

import * as Location from 'expo-location';

async function checkLocationServices() {
  try {
    const enabled =
      await Location.hasServicesEnabledAsync();

    if (enabled) {
      console.log('Location services are enabled.');
    } else {
      console.log('Location services are disabled.');
    }

    return enabled;
  } catch (error) {
    console.error('Unable to check location services:', error);
    return false;
  }
}

10.2 Recommended User Experience

  • Explain that location services need to be enabled.
  • Provide instructions for changing the relevant device setting.
  • Do not repeatedly request permission when the problem is a disabled system service.
  • Recheck service availability when the user returns to the application.

11. Geocoding and Reverse Geocoding

Geocoding and reverse geocoding convert between written addresses and geographical coordinates.

11.1 Geocoding

Geocoding converts a human-readable address into latitude and longitude.

Example: A user enters an address, and the application retrieves coordinates for a map marker.

import * as Location from 'expo-location';

async function findCoordinates(address) {
  try {
    const results = await Location.geocodeAsync(address);

    if (results.length === 0) {
      return null;
    }

    return {
      latitude: results[0].latitude,
      longitude: results[0].longitude
    };
  } catch (error) {
    console.error('Geocoding error:', error);
    return null;
  }
}

11.2 Reverse Geocoding

Reverse geocoding converts coordinates into a human-readable address or place description, when the provider can resolve it.

import * as Location from 'expo-location';

async function getAddress(latitude, longitude) {
  try {
    const results = await Location.reverseGeocodeAsync({
      latitude,
      longitude
    });

    if (results.length === 0) {
      return 'Address not available';
    }

    const place = results[0];

    return [
      place.name,
      place.street,
      place.city,
      place.region,
      place.postalCode,
      place.country
    ]
      .filter(Boolean)
      .join(', ');
  } catch (error) {
    console.error('Reverse geocoding error:', error);
    return 'Unable to find address';
  }
}

11.3 Geocoding Best Practices

  • Handle empty results and errors.
  • Avoid sending excessive geocoding requests.
  • Do not assume every coordinate maps to a complete street address.
  • Consider the provider's rate limits and usage policies.
  • Request foreground permission where required by the library and platform.
  • Display address results as estimates when the provider cannot guarantee exactness.

12. Displaying Location on a Map

A map interface can display a location marker and help users understand where a coordinate is situated. React Native applications can use compatible map libraries or a mapping provider's supported SDK.

12.1 Typical Map Integration Steps

  1. Choose a map library and confirm its Android and iOS requirements.
  2. Install and configure the required native dependencies.
  3. Retrieve the location with appropriate permission.
  4. Pass latitude and longitude to the map's region or camera configuration.
  5. Display a marker for the current or selected location.
  6. Handle loading, permission denial, and unavailable location data.

12.2 Example Coordinate Data

const userLocation = {
  latitude: 19.0760,
  longitude: 72.8777
};

The coordinates above are illustrative sample data. A map library may require additional properties, an initial region, or a map-provider configuration. Refer to the documentation for the map library selected for the project.

13. Calculating Distance Between Two Locations

Location coordinates can be used to estimate the straight-line distance between two points. This is useful for nearby searches or approximate distance displays.

The Haversine formula estimates the great-circle distance between two points on a sphere.

function toRadians(degrees) {
  return degrees * Math.PI / 180;
}

function calculateDistance(lat1, lon1, lat2, lon2) {
  const earthRadiusKm = 6371;

  const dLat = toRadians(lat2 - lat1);
  const dLon = toRadians(lon2 - lon1);

  const a =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(toRadians(lat1)) *
    Math.cos(toRadians(lat2)) *
    Math.sin(dLon / 2) ** 2;

  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  return earthRadiusKm * c;
}

const distance = calculateDistance(
  19.0760,
  72.8777,
  19.0896,
  72.8656
);

console.log(`Distance: ${distance.toFixed(2)} km`);

This calculation provides a straight-line estimate, not driving or walking distance. Real routes require a routing or directions service. Accuracy is also limited by the quality of the input coordinates.

14. Foreground vs. Background Location Tracking

Aspect Foreground Location Background Location
Typical use Current location displayed while using the app. Tracking a user-authorized activity when the app is not visible.
Permissions Foreground authorization. Additional background authorization and native configuration may be required.
Complexity Generally simpler to implement. More complex due to platform policies and lifecycle behavior.
Battery impact Depends on update frequency and accuracy. Can be significant if tracking continues unnecessarily.
Platform limitations Subject to device and operating-system behavior. Subject to additional restrictions and background execution policies.

14.1 Background Location Considerations

  • Request foreground permission before requesting background access where required.
  • Explain the ongoing tracking purpose before requesting additional authorization.
  • Configure the required background modes or permissions.
  • Use a supported development or production build where required.
  • Do not assume tracking continues after the application is force-stopped or terminated.
  • Provide a clear way for users to stop tracking.
  • Check the current platform and app-store policies before release.

15. Geofencing

Geofencing uses a geographical region to trigger an event when a device enters or leaves a defined area. A geofence is often represented by a centre coordinate and a radius.

15.1 Example Use Cases

  • Notifying a user when approaching a selected destination.
  • Triggering a reminder when entering a defined area.
  • Supporting location-based attendance workflows with appropriate safeguards.
  • Providing alerts when a delivery reaches a designated region.

15.2 Geofencing Workflow

  1. Define the geographical regions and their identifiers.
  2. Request the required location permissions.
  3. Configure the library's geofencing or region-monitoring support.
  4. Register the regions with the platform.
  5. Handle entry and exit events.
  6. Remove unused regions and stop monitoring when the feature ends.

Geofencing is subject to platform limits, background restrictions, and location accuracy. It should not be treated as a guaranteed real-time boundary detector.

16. Error Handling and Troubleshooting

Problem Possible Cause Recommended Solution
Permission denied The user refused location access. Explain the limitation and offer a manual alternative.
Location services disabled Device location settings are off. Ask the user to enable the required service.
Location request is slow Weak GPS signals or poor connectivity. Show a loading state and handle timeout or failure.
Coordinates are inaccurate Indoor environment or weak signals. Check the reported accuracy and allow a new measurement.
No last-known location The operating system has no suitable cached position. Request a fresh location measurement.
Address not found Reverse geocoding returned no results. Display coordinates or a useful fallback message.
Updates continue unnecessarily Location subscription was not removed. Remove the subscription when tracking ends.
Background tracking fails Missing permission, configuration, or platform support. Verify the library documentation and native build settings.

16.1 General Error-Handling Pattern

async function safelyGetLocation() {
  try {
    const permission =
      await Location.requestForegroundPermissionsAsync();

    if (!permission.granted) {
      return {
        success: false,
        message: 'Location permission was denied.'
      };
    }

    const location =
      await Location.getCurrentPositionAsync({});

    return {
      success: true,
      location
    };
  } catch (error) {
    console.error('Location operation failed:', error);

    return {
      success: false,
      message: 'Unable to retrieve location.'
    };
  }
}

17. Privacy, Security, and Battery Best Practices

  • Request only the location access needed for the current feature.
  • Clearly explain why location is being collected.
  • Prefer foreground tracking unless background tracking is essential.
  • Stop updates when the user finishes the task.
  • Choose an appropriate accuracy level and update frequency.
  • Avoid collecting location continuously without a clear purpose.
  • Protect location information when storing or transmitting it.
  • Use secure network communication when sending coordinates to a server.
  • Do not expose sensitive coordinates in public logs or analytics.
  • Provide a clear way to disable location-dependent features.

18. Testing Location Features

Location features should be tested across devices, operating-system versions, and permission states. Simulators can provide simulated coordinates, but physical devices are important for validating real GPS behavior.

18.1 Testing Checklist

  • Test when location permission is granted.
  • Test when permission is denied or restricted.
  • Test when device location services are disabled.
  • Test indoors and outdoors.
  • Test when location retrieval takes longer than expected.
  • Test when no last-known location is available.
  • Test when the application moves to the background.
  • Verify that subscriptions are removed correctly.
  • Test approximate and precise permission choices where available.
  • Confirm that the app remains usable without location access.

19. Practical Project: GPS Location Finder

Project Objective: Build a React Native application that requests location permission and displays the current coordinates and reported accuracy.

19.1 Project Requirements

  • Provide a button to request the current location.
  • Display permission and loading states.
  • Show latitude and longitude.
  • Show reported accuracy where available.
  • Handle disabled location services.
  • Display a friendly message when permission is denied.
  • Provide an option to retrieve the location again.
  • Optionally display the location on a map.

19.2 Suggested Folder Structure

GPSLocationFinder/
├── App.js
├── screens/
│   └── LocationScreen.js
├── components/
│   ├── LocationDetails.js
│   ├── PermissionMessage.js
│   └── LoadingIndicator.js
└── package.json

19.3 Development Steps

  1. Create an Expo React Native project.
  2. Install expo-location.
  3. Configure the required platform permission descriptions.
  4. Create a location screen with a button.
  5. Request foreground permission before accessing coordinates.
  6. Check service availability and retrieve the current position.
  7. Display the coordinates and accuracy.
  8. Handle errors, denial, and missing location data.
  9. Test on an emulator and a physical device.

19.4 Expected Result

The application should display location information after the user grants permission and the device provides a location estimate. If permission is denied or location services are unavailable, the application should display a helpful message instead of crashing.

20. Practice Exercises

  1. Create a screen that requests foreground location permission.
  2. Display the current latitude and longitude.
  3. Display the accuracy reported by the location provider.
  4. Retrieve the last-known location and check its timestamp.
  5. Subscribe to location updates and clean up the subscription.
  6. Check whether location services are enabled.
  7. Convert a typed address into coordinates using geocoding.
  8. Convert coordinates into an address using reverse geocoding.
  9. Calculate straight-line distance between two coordinates.
  10. Design a map screen that shows the current location.
  11. Handle permission denial and provide a manual-entry alternative.
  12. Research the configuration required for a background location feature.

21. Interview Questions and Answers

Q1. What is GPS?

Answer: GPS is a satellite-based positioning system that helps compatible devices estimate their geographical position.

Q2. Is GPS the only source of mobile location information?

Answer: No. Mobile location services may combine GPS, Wi-Fi, cellular, and other supported sources.

Q3. What are latitude and longitude?

Answer: Latitude represents position north or south of the equator, while longitude represents position east or west of the prime meridian.

Q4. Which library can be used for location in an Expo React Native application?

Answer: The expo-location package provides APIs for location permissions, current coordinates, location updates, and geocoding.

Q5. What is foreground location permission?

Answer: It allows an application to access location while it is in use, subject to operating-system rules.

Q6. What is background location permission?

Answer: It authorizes supported location operations while the application is not actively visible, subject to additional permissions and restrictions.

Q7. What is the difference between current and last-known location?

Answer: Current location requests a new measurement. Last-known location retrieves a previously available position, which may be faster but can be stale or unavailable.

Q8. What is reverse geocoding?

Answer: Reverse geocoding converts latitude and longitude into a human-readable address or place description when the provider can resolve it.

Q9. What is geofencing?

Answer: Geofencing monitors defined geographical regions and can trigger events when a device enters or leaves a region.

Q10. Why should location subscriptions be removed?

Answer: Removing subscriptions prevents unnecessary updates, reduces battery use, and avoids unwanted state updates after a component unmounts.

Q11. Why can location retrieval be inaccurate indoors?

Answer: Indoor environments can weaken or obstruct satellite signals and affect the quality of location measurements.

Q12. How can an application reduce location-related battery consumption?

Answer: Request only necessary accuracy, reduce update frequency, use one-time requests when suitable, and stop tracking when the feature is no longer active.

22. Quick Revision Checklist

  • GPS is a satellite-based positioning system.
  • Mobile location services may combine multiple location sources.
  • Latitude and longitude identify geographical coordinates.
  • Location APIs can retrieve current positions and last-known positions.
  • Foreground and background permissions have different requirements.
  • Geocoding converts addresses into coordinates.
  • Reverse geocoding converts coordinates into address information.
  • Geofencing monitors defined geographical regions.
  • Accuracy, update frequency, and battery consumption must be considered together.
  • Location subscriptions must be cleaned up when no longer needed.
  • Privacy and permission handling are essential for location-based applications.

23. Conclusion

Accessing location and GPS services is an important skill for React Native developers building navigation, delivery, travel, fitness, and location-aware applications. With a compatible library such as Expo Location, developers can request permission, retrieve coordinates, subscribe to location changes, and perform geocoding operations.

A reliable implementation must account for location accuracy, disabled services, permission denial, platform restrictions, battery consumption, and user privacy. Start with foreground location access, request only the information the application needs, and add background tracking only when the feature genuinely requires it.

24. Learning Resources

whatsapp